import { NavBar, DatePicker } from 'antd-mobile'
import './month.scss'
import { useEffect, useMemo, useState } from 'react'
import classNames from 'classnames'
import dayjs from 'dayjs'
import lodash from 'lodash'
import { useSelector } from 'react-redux'
import DailyBill from '@/page/Month/components/dayBill/dayBill'

const Month = () => {
    const storeCurrentMonth = useSelector(state => state.bill.currentMonth)
    const billList = useSelector(state => state.bill.billList)
    const [dateVisible, setDateVisible] = useState(false)
    //月份分组后的账单数据
    const [currentMonthList, setMonthList] = useState([])
    //月份key，初始为当前月
    const [currentMonth, setCurrentMonth] = useState(storeCurrentMonth)

    //根据获取到的时间作为key，月分组的账单数组
    const monthGroup = useMemo(() => {
        return lodash.groupBy(billList, item => {
            return dayjs(item.date).format('YYYY-MM')
        })
    }, [billList])

    //根据当前月的账单，以天为单位分组
    const dayGroup = useMemo(() => {
        const dayResult = lodash.groupBy(currentMonthList, item => {
            return dayjs(item.date).format('YYYY-MM-DD')
        })
        const dayKeys = Object.keys(dayResult)
        return {dayResult,dayKeys}
    }, [currentMonthList])

    //时间选择器 确认事件
    const dateConfirm = (dateVal) => {
        setDateVisible(false)

        //月显示
        const monthKey = dayjs(dateVal).format('YYYY-MM')
        setCurrentMonth(monthKey)

        //按月分组后数据
        setMonthList(monthGroup[monthKey])
    }

    //首次加载
    useEffect(()=>{
        //阻止页面默认滑动，避免浏览器触发返回
        const preventTouchMove = (e)=>{
          e.preventDefault?.()
          e.returnValue = false
        }
        document.addEventListener('touchmove',preventTouchMove,{passive:false})

        const list = monthGroup[storeCurrentMonth]
        if(list){
            setMonthList(list)
        }

        //组件卸载时恢复页面默认滑动
        return ()=>{
          document.removeEventListener('touchmove',preventTouchMove)
        }

    },[monthGroup,storeCurrentMonth])

    // 计算统计
    const monthResult = useMemo(() => {
        if(currentMonthList){
            //收入
            const income = currentMonthList.filter(item => item.type === 'income')
                .reduce((a, c) => a + c.money, 0)
            //支出
            const pay = currentMonthList.filter(item => item.type === 'pay')
                .reduce((a, c) => a + c.money, 0)
            return { income, pay, total: income + pay }
        }else{
            return { income:0, pay:0, total: 0 }
        }
    }, [currentMonthList])

    return (
        <div className="monthlyBill">
            <NavBar className="nav" backIcon={false}>
                月度收支
            </NavBar>
            <div className="content">
                <div className="header">
                    {/* 时间切换区域 */}
                    <div className="date" onClick={() => setDateVisible(true)}>
                        <span className="text">
                            {currentMonth}月账单
                        </span>
                        <span className={classNames({ 'arrow': true, 'expand': dateVisible })} ></span>
                    </div>
                    {/* 统计区域 */}
                    <div className='twoLineOverview'>
                        <div className="item">
                            <span className="money">{monthResult.pay.toFixed(2)}</span>
                            <span className="type">支出</span>
                        </div>
                        <div className="item">
                            <span className="money">{monthResult.income.toFixed(2)}</span>
                            <span className="type">收入</span>
                        </div>
                        <div className="item">
                            <span className="money">{monthResult.total.toFixed(2)}</span>
                            <span className="type">结余</span>
                        </div>
                    </div>
                    {/* 时间选择器 */}
                    <DatePicker
                        className="kaDate"
                        title="记账日期"
                        precision="month"
                        visible={dateVisible}
                        max={new Date()}
                        onClose={() => setDateVisible(false)}
                        onConfirm={dateConfirm}
                    />
                </div>
                {dayGroup.dayKeys.map((dayKey)=>{
                    return <DailyBill key={dayKey} dayKey={dayKey} dayBillList={dayGroup.dayResult[dayKey]}/>
                })}
            </div>
        </div >
    )
}

export default Month